//
//  CTFliterCollectionView.m
//  ConstellationTalk_0.1
//
//  Created by 韩威 on 15/7/5.
//  Copyright (c) 2015年 riley chu. All rights reserved.
//

#import "CTFliterCollectionView.h"
#import "CTFliterCollectionCell.h"

#import "CTHeader.h"
#import "CTDebugManager.h"

#import "UIImage+Utility.h"

@interface CTFliterCollectionView()<UICollectionViewDataSource,UICollectionViewDelegate>
{
    CGSize size;
    UICollectionView *userFeaturesCollectionView;
    NSArray          *filterAry;
    NSArray          *filterNameAry;
    UIImage          *filterImage;
    UIImage          *filterIconImage;
    NSMutableArray   *filterImageArray;
}

@end

@implementation CTFliterCollectionView

@synthesize delegate;

- (void)dealloc
{
    delegate = nil;
    filterAry = nil;
    filterNameAry  = nil;
    [userFeaturesCollectionView removeFromSuperview];
    userFeaturesCollectionView = nil;
    filterImage = nil;
    [CTDebugManager showDebugLogInfo:@"dealloc : CTFliterCollectionView Is Removed!!!"];
}


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        //        self.frame = CGRectMake(0, 0, CT_HEADER_SCREEN_WIDTH, 95);
//        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.16];
//        self.backgroundColor = []
        size = CGSizeMake(60, 128);
        [self setFilters];
        [self createUserCollectionView];
    }
    return self;
}
- (void)setFilters
{
    filterAry = @[
                 @{@"name":@"Original",                 @"title":@"None",       @"version":@(0.0)},
                 @{@"name":@"CISRGBToneCurveToLinear",  @"title":@"Linear",     @"version":@(7.0)},
                 @{@"name":@"CIVignetteEffect",         @"title":@"Vignette",   @"version":@(7.0)},
                 @{@"name":@"CIPhotoEffectInstant",     @"title":@"Instant",    @"version":@(7.0)},
                 @{@"name":@"CIPhotoEffectProcess",     @"title":@"Process",    @"version":@(7.0)},
                 @{@"name":@"CIPhotoEffectTransfer",    @"title":@"Transfer",   @"version":@(7.0)},
                 @{@"name":@"CISepiaTone",              @"title":@"Sepia",      @"version":@(5.0)},
                 @{@"name":@"CIPhotoEffectChrome",      @"title":@"Chrome",     @"version":@(7.0)},
                 @{@"name":@"CIPhotoEffectFade",        @"title":@"Fade",       @"version":@(7.0)},
                 @{@"name":@"CILinearToSRGBToneCurve",  @"title":@"Curve",      @"version":@(7.0)},
                 @{@"name":@"CIPhotoEffectTonal",       @"title":@"Tonal",      @"version":@(7.0)},
                 @{@"name":@"CIPhotoEffectNoir",        @"title":@"Noir",       @"version":@(7.0)},
                 @{@"name":@"CIPhotoEffectMono",        @"title":@"Mono",       @"version":@(7.0)},
                 @{@"name":@"CIColorInvert",            @"title":@"Invert",     @"version":@(6.0)},
                 ];
    filterNameAry = @[@"原图",@"蓝调",@"哥特",@"迷情",@"珊瑚",@"暮秋",@"复古",@"苦艾",@"云端",@"梦幻",@"流年",@"黑白",@"天使之吻",@"曝光"];
}

//创建CollectionView
- (void)createUserCollectionView
{
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    //    flowLayout.headerReferenceSize = CGSizeMake(CT_HEADER_SCREEN_WIDTH, 0);//头部
    userFeaturesCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,0, CT_HEADER_SCREEN_WIDTH, size.height) collectionViewLayout:flowLayout];
    // homePageCollectionView.showsVerticalScrollIndicator = NO;
    userFeaturesCollectionView.delegate = self;
    userFeaturesCollectionView.dataSource = self;
    [self addSubview:userFeaturesCollectionView];
    userFeaturesCollectionView.backgroundColor = [UIColor clearColor];
    [userFeaturesCollectionView registerClass:[CTFliterCollectionCell class] forCellWithReuseIdentifier:@"cell"];
    [userFeaturesCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ReusableView"];
}
#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
//    if (filterImageArray.count > 0)
//    {
    return filterImageArray.count;

//    }
//    else return 0;
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identify = @"cell";
    
    CTFliterCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
//    cell.backgroundColor = [UIColor clearColor];
    [cell sizeToFit];
//    filterImageArray.count
//    if (filterImageArray.count > 0)
//    {
        cell.image = [filterImageArray objectAtIndex:indexPath.row];

//    }
    cell.strTitle = [filterNameAry objectAtIndex:indexPath.row];
    

//    if ([[emojiDetailItemArray objectAtIndex:indexPath.row] isKindOfClass:[CTEditeBubbleListItem class]])
//    {
//        CTEditeBubbleListItem *item = [emojiDetailItemArray objectAtIndex:indexPath.row];
//        cell.bubbleItem = item;
//    }
//    else
//    {
//        CTEditeEmojiListDetailsItem *item = [emojiDetailItemArray objectAtIndex:indexPath.row];
//        cell.imgUrl = item.thumb;
//    }
    
    return cell;
}

//头部显示的内容
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:
                                            UICollectionElementKindSectionHeader withReuseIdentifier:@"ReusableView" forIndexPath:indexPath];
    
    //    [headerView addSubview:advertisingColumnView];//头部广告栏
    return headerView;
}

#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return size;
    
}
//定义每个UICollectionView 的间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(1,1,1,20);
}
//定义UICollectionView 每个item的纵向间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 25;
}

//定义每个UICollectionView 纵向的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
   //    else
//    {
        NSDictionary *dic;
        NSString * str;
        dic = [filterAry objectAtIndex:(indexPath.row)];
        str = [dic objectForKey:@"name"];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            UIImage *fImage = [self filteredImage:filterImage withFilterName:
                               str];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //            adjustOriginalImageView.image = image;
                //            adjustView.image = image;
                if (indexPath.row == 0)
                {
                    if ([self.delegate respondsToSelector:@selector(filterCollectionViewDidSelected:withImage:)])
                    {
                        [self.delegate filterCollectionViewDidSelected:self withImage:filterImage];
                    }
                }
                else
                {
                    if ([self.delegate respondsToSelector:@selector(filterCollectionViewDidSelected:withImage:)])
                    {
                        [self.delegate filterCollectionViewDidSelected:self withImage:fImage];
                    }
                }
                
            });
            
        });

//    }
    
}
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


- (void)setFilterImageArrayWithImage:(UIImage *)image
{
    filterImageArray = [NSMutableArray array];
    for (int i = 0; i < filterAry.count ; i++)
    {
        NSDictionary *dic;
        NSString * str;
        dic = [filterAry objectAtIndex:i];
        str = [dic objectForKey:@"name"];
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
            UIImage *iconImage = [self filteredImage:image withFilterName:str];
            
//            dispatch_async(dispatch_get_main_queue(), ^{
                [filterImageArray addObject:iconImage];
//            });
//        });

    }
}
- (UIImage*)filteredImage:(UIImage*)image withFilterName:(NSString*)filterName
{
    if([filterName isEqualToString:@"Original"]){
        return filterIconImage;
    }
    
    CIImage *ciImage = [[CIImage alloc] initWithImage:image];
    CIFilter *filter = [CIFilter filterWithName:filterName keysAndValues:kCIInputImageKey, ciImage, nil];
    
    //        [filter setDefaults];
    
    if([filterName isEqualToString:@"CIVignetteEffect"]){
        // parameters for CIVignetteEffect
        CGFloat R = MIN(image.size.width, image.size.height)/2;
        CIVector *vct = [[CIVector alloc] initWithX:image.size.width/2 Y:image.size.height/2];
        [filter setValue:vct forKey:@"inputCenter"];
        [filter setValue:[NSNumber numberWithFloat:0.9] forKey:@"inputIntensity"];
        [filter setValue:[NSNumber numberWithFloat:R] forKey:@"inputRadius"];
    }
    
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *outputImage = [filter outputImage];
    CGImageRef cgImage = [context createCGImage:outputImage fromRect:[outputImage extent]];
    
    UIImage *result = [UIImage imageWithCGImage:cgImage];
    
    CGImageRelease(cgImage);
    
    return result;
}

#pragma mark -setter-
- (void)setFliterImage:(UIImage *)filterImg
{
    float   image_x = filterImg.size.width;
    float   image_y = filterImg.size.height;
    filterImage = [filterImg aspectFill:CGSizeMake(image_x, image_y)];
    filterIconImage = [filterImg aspectFill:CGSizeMake(60, 60)];
    [self setFilterImageArrayWithImage:filterIconImage];
    [userFeaturesCollectionView reloadData];
}


@end
